package net.kuratkoo.jidelnicekvut;

import android.content.Context;
import android.text.Html;
import android.util.Log;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class FoodSet extends ArrayList<Food> {

    private Context context;
    private static final String TAG = "JidelnicekVUT|FoodSet";

    public FoodSet(Context context) {
        this.context = context;
    }

    public FoodSet getByCanteenId(Integer canteenId) throws MyHttpClientException {
        this.clear();
        MyHttpClient mhc = new MyHttpClient(Constants.CANTEEN_DETAIL_URL + canteenId);
        mhc.execute();
        String content = mhc.getResponse();
        Pattern p = Pattern.compile("</span>([^<]+)<span class=\"gram\"><br/>[^<]+</span></td><td class=\"levyjid fs[1|2]\" onClick=\"slo\\(([0-9]+)\\)\">([^<]+)</td><td class=\"pravy slcen1\">([0-9]+),-&nbsp;</td><td class=\"pravy slcen2\">([0-9]+),-&nbsp;</td><td class=\"pravy slcen3\">([0-9]+),-&nbsp;</td></tr>");
        Matcher m = p.matcher(content);
        while (m.find()) {
            MatchResult mr = m.toMatchResult();
            Food food = new Food(this.context);
            food.canteenId = canteenId;
            food.type = mr.group(1);
            food.food = mr.group(3);
            food.price1 = Integer.parseInt(mr.group(4));
            food.price2 = Integer.parseInt(mr.group(5));
            food.price3 = Integer.parseInt(mr.group(6));

            Pattern pa = Pattern.compile("a\\[" + mr.group(2) + "\\] = \"([^\"]*)\";");
            Matcher ma = pa.matcher(content);
            if (ma.find()) {
                food.contents = Html.fromHtml(ma.group(1).replaceAll("<br/>", "###")).toString().replace("###", "\n").trim();
                if (food.contents.indexOf("\n\n") > -1) {
                    food.contents = food.contents.substring(food.contents.indexOf("\n\n") + 2);
                } else {
                    food.contents = "Neuvedeno";
                }
            }
            this.add(food);
        }

        /** Load votes **/
        if (!this.isEmpty()) {
            try {
                MyHttpClient mhcv = new MyHttpClient(Constants.VOTE_GET_URL_API);
                mhcv.setPostData("canteenId", canteenId.toString());
                for (Food food : this) {
                    mhcv.setPostData("food[]", food.food);
                }
                mhcv.execute();
                Document doc = XML.stringToXml(mhcv.getResponse());
                NodeList votes = doc.getElementsByTagName("food");
                for (int k = 0; k < votes.getLength(); k++) {
                    this.get(k).votes = Float.parseFloat(XML.getValue((Element) votes.item(k), "score"));
                    this.get(k).voteCount = Integer.parseInt(XML.getValue((Element) votes.item(k), "votes"));
                }
            } catch (Exception e) {
                Log.e(TAG, "Error: " + e.getLocalizedMessage());
            }
        }

        return this.sort();
    }

    public FoodSet sort() {
        if (Preferences.getString(context, "keywords", "").trim().length() > 0) {
            List<String> l = Arrays.asList(Preferences.getString(context, "keywords", "").trim().split(","));
            for (Food food : this) {
                for (int j = 0; j < l.size(); j++) {
                    if (food.food.toLowerCase().contains(l.get(j).trim().toLowerCase()) || food.contents.toLowerCase().contains(l.get(j).trim().toLowerCase())) {
                        food.isKeyword = true;
                        break;
                    }
                }
            }
        }

        if (Preferences.getString(context, "food", "name").equals("name")) {
            Collections.sort(this, new Comparator<Food>() {

                public int compare(Food f1, Food f2) {
                    Collator c = Collator.getInstance(new Locale("cs", "CZ"));
                    return c.compare(f1.food, f2.food);
                }
            });
        } else if (Preferences.getString(context, "food", "name").equals("price")) {
            final String pricing = Preferences.getString(context, "price", "stud");
            Collections.sort(this, new Comparator<Food>() {

                public int compare(Food f1, Food f2) {
                    if (pricing.equals("stud")) {
                        return f1.price1.compareTo(f2.price1);
                    } else if (pricing.equals("empl")) {
                        return f1.price2.compareTo(f2.price2);
                    } else if (pricing.equals("other")) {
                        return f1.price3.compareTo(f2.price3);
                    } else {
                        return f1.price1.compareTo(f2.price1);
                    }
                }
            });
        } else if (Preferences.getString(context, "food", "name").equals("keyword")) {
            Collections.sort(this, new Comparator<Food>() {

                public int compare(Food f1, Food f2) {
                    return f2.isKeyword.compareTo(f1.isKeyword);
                }
            });
        } else if (Preferences.getString(context, "food", "name").equals("votes")) {
            Collections.sort(this, new Comparator<Food>() {

                public int compare(Food f1, Food f2) {
                    return f2.votes.compareTo(f1.votes);
                }
            });
        }
        return this;
    }
}
